'use strict';

const Service = require('egg').Service;

const svgCaptcha = require("svg-captcha");

class LoginService extends Service {
  async captchaImage() {
    let captcha = svgCaptcha.create({
      // color:true,
      noise:2,
      ignoreChars:"0o1i",
      size:4,
      background:"#aaa"
    });
    return captcha;
  }
  async login(params){
    if(!this.ctx.session.login_code) {
      return {
        code:411,
        msg:'请先获取验证码'
      }
    }
    let code = this.ctx.session.login_code.toLocaleLowerCase();
    if(params.code.toLocaleLowerCase() === code){
      return await this.adjust(params);
    }else {
      return {
        code:500,
        msg:'验证码错误'
      }
    }
  }
  async adjust(user){
    const {ctx,app} = this;
    let result = await ctx.model.SysUser.findOne({
      where:{
        user_name:user.username
      },
      include:[ctx.model.SysRole]
    });
    if(result){
      let _user = result.toJSON();
      if(_user.password === user.password){
        const token = app.jwt.sign({
          username:user.username
        },app.config.jwt.secret,{
          expiresIn:"60m"
        });
        // 更新登陆时间
        result.update({loginDate:new Date()});
        return {
          code:200,
          token,
          data:_user,
          msg:"登录成功"
        }
      }else{
        return {
          code:400,
          msg:"密码不正确"
        }
      }
    }else{
      return {
        code:400,
        msg:"该账号未注册"
      }
    }
  }
}

module.exports = LoginService;
